package de.karlNet.sambamanager.view.beans.forms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Controller;

import de.karlNet.sambamanager.ldapController.LdapMemberOfTree;
import de.karlNet.sambamanager.ldapController.commands.macros.ModifyUserMacro;
import de.karlNet.sambamanager.ldapModel.LdapUser;
import de.karlNet.sambamanager.ldapModel.dto.LdapUserCreationDTO;

@Controller
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class EditUserBean extends CreateUserBean {
	@Autowired
	private LdapMemberOfTree ldapMemberOfTree;
	@Autowired
	private SelectableGroupTree groupTree;
	@Autowired
	private ModifyUserMacro modifyUserMacro;

	@Override
	public void setShow(boolean show) {
		this.ldapUserCreationDTO = new LdapUserCreationDTO();
		this.ldapUserCreationDTO
				.setLdapUser((LdapUser) this.nodeContainer.selectedNode
						.getLdapObject());
		this.groupTree.reset();
		this.groupTree.setPreSelectedNodes(this.ldapMemberOfTree
				.getChildrenOfDN(this.ldapUserCreationDTO.getLdapUser().getDn()));
		
		super.setShow(show);
	}

	@Override
	public String create() {
		this.ldapUserCreationDTO.getMemberShips().addAll(this.groupTree.getSelectedGroups());
		try {
			this.modifyUserMacro.updateUser(this.ldapUserCreationDTO);
			this.ldapUserCreationDTO = new LdapUserCreationDTO();
			this.setShow(false);
			return "index.xhtml";
		} catch (Exception e) {
			this.showErrorMessage(e.getMessage());
			return "";
		}
	}
	
	@Override
	public String getPageName() {
		return "editUserView";
	}
}
